import { ApiCall, TsrpcError } from "tsrpc";
import { masterServer } from "../../MasterServerMain";
import { ReqLogin, ResLogin } from "../../shared/protocols/masterServer/PtlLogin";
import { DBUser } from "../DBUser";
import { DBMail } from "../DBMail";

export async function ApiLogin(call: ApiCall<ReqLogin, ResLogin>) {

    let userInfo = DBUser.getUserInfoWithPassword(call.req.account, call.req.password);

    if (!userInfo) {
        call.error('USER_NOT_EXISTS');
        return;
    }

    let token = DBUser.generateToken(call.req.account + call.req.password + Date.now().toString());
    let subWorldId = userInfo.subWorldId;
    if (subWorldId) {
        let s = masterServer.getSubWorldServer(subWorldId);
        //if can not find server, clear.
        subWorldId = s ? subWorldId : '';
    }

    DBUser.updateUserData(call.req.account, { token: token, subWorldId: subWorldId });

    DBMail.insterNewMail('system', userInfo.uid!, '欢迎登录', userInfo.name + '，你好！\n这封邮件会在你每次登录的时候收到，如果不需要，请在 ApiLogin.ts 中删除相关代码即可。');

    call.succ({
        token: token,
        userInfo: {
            name: userInfo.name,
            visualId: userInfo.visualId,
            uid: userInfo.uid!,
            gender: userInfo.gender,
            introduction: userInfo.introduction,
        },
        subWorldId: subWorldId!
    });
}